/**
 * 文件类型配置管理
 * 统一管理所有组件的文件类型配置
 */

// 扩展名到MIME类型的映射
export const EXTENSION_TO_MIME: Record<string, string> = {
  // 文档类型
  ".docx":
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  ".pdf": "application/pdf",
  ".doc": "application/msword",
  ".txt": "text/plain",
  ".rtf": "application/rtf",

  // 图片类型
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png",
  ".gif": "image/gif",
  ".bmp": "image/bmp",
  ".webp": "image/webp",
  ".svg": "image/svg+xml",

  // 视频类型
  ".mp4": "video/mp4",
  ".avi": "video/avi",
  ".mov": "video/quicktime",
  ".wmv": "video/x-ms-wmv",
  ".flv": "video/x-flv",
  ".mkv": "video/x-matroska",
  ".webm": "video/webm",

  // 音频类型
  ".mp3": "audio/mpeg",
  ".wav": "audio/wav",
  ".flac": "audio/flac",
  ".aac": "audio/aac",
  ".ogg": "audio/ogg",
  ".m4a": "audio/mp4"
};

// 默认文件大小限制配置
const DEFAULT_SIZE_LIMITS: Record<string, number> = {
  // 图片类型 - 15MB
  ".jpg": 15,
  ".jpeg": 15,
  ".png": 15,
  ".gif": 15,
  ".bmp": 15,
  ".webp": 15,
  ".svg": 15,
  // 文档类型 - 20MB
  ".docx": 20,
  ".pdf": 20,
  ".doc": 20,
  ".txt": 20,
  ".rtf": 20,
  // 视频类型 - 2GB
  ".mp4": 2048,
  ".avi": 2048,
  ".mov": 2048,
  ".wmv": 2048,
  ".flv": 2048,
  ".mkv": 2048,
  ".webm": 2048,
  // 音频类型 - 100MB
  ".mp3": 100,
  ".wav": 100,
  ".flac": 100,
  ".aac": 100,
  ".ogg": 100,
  ".m4a": 100
};

/**
 * 根据扩展名字符串生成accept属性
 * @param extensions 扩展名字符串，如 ".docx,.pdf"
 * @returns accept属性值，包含扩展名和对应的MIME类型
 */
export function generateAccept(extensions: string): string {
  if (!extensions) return "*/*";

  const extList = extensions.split(",").map(ext => ext.trim());
  const acceptList: string[] = [];

  extList.forEach(ext => {
    // 添加扩展名
    acceptList.push(ext);
    // 添加对应的MIME类型
    const mimeType = EXTENSION_TO_MIME[ext.toLowerCase()];
    if (mimeType && !acceptList.includes(mimeType)) {
      acceptList.push(mimeType);
    }
  });

  return acceptList.join(",");
}

/**
 * 验证文件类型
 * @param file 文件对象
 * @param extensions 允许的扩展名字符串，如 ".docx,.pdf"
 */
export function validateFileType(file: File, extensions: string): boolean {
  if (!extensions) return true;

  const extList = extensions.split(",").map(ext => ext.trim().toLowerCase());
  const fileName = file.name.toLowerCase();
  const fileType = file.type.toLowerCase();

  // 检查扩展名
  const extensionValid = extList.some(ext => fileName.endsWith(ext));

  // 检查MIME类型
  const mimeTypeValid = extList.some(ext => {
    const mimeType = EXTENSION_TO_MIME[ext];
    return mimeType && fileType === mimeType.toLowerCase();
  });

  return extensionValid || mimeTypeValid;
}

/**
 * 验证文件大小
 * @param file 文件对象
 * @param extensions 扩展名字符串
 * @param customMaxSize 自定义最大大小(MB)，优先级高于默认配置
 */
export function validateFileSize(
  file: File,
  extensions: string,
  customMaxSize?: number
): boolean {
  if (customMaxSize !== undefined) {
    return file.size <= customMaxSize * 1024 * 1024;
  }

  if (!extensions) return true;

  const fileName = file.name.toLowerCase();
  const extList = extensions.split(",").map(ext => ext.trim().toLowerCase());

  // 找到匹配的扩展名并获取其大小限制
  const matchedExt = extList.find(ext => fileName.endsWith(ext));
  if (matchedExt) {
    const maxSize = DEFAULT_SIZE_LIMITS[matchedExt] || 20; // 默认20MB
    return file.size <= maxSize * 1024 * 1024;
  }

  return true;
}

/**
 * 获取文件类型错误信息
 */
export function getFileTypeErrorMessage(extensions: string): string {
  if (!extensions) return "文件类型不符合要求";

  const extList = extensions.split(",").map(ext => ext.trim().replace(".", ""));
  return `只支持 ${extList.join("、")} 格式的文件`;
}

/**
 * 获取文件大小错误信息
 */
export function getFileSizeErrorMessage(
  extensions: string,
  customMaxSize?: number
): string {
  if (customMaxSize !== undefined) {
    return `文件大小不能超过 ${customMaxSize}MB`;
  }

  if (!extensions) return "文件大小超出限制";

  const fileName = extensions.split(",")[0]?.trim().toLowerCase();
  const maxSize = DEFAULT_SIZE_LIMITS[fileName] || 20;
  return `文件大小不能超过 ${maxSize}MB`;
}

/**
 * 格式化文件大小显示
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}

/**
 * 获取文件类型提示文本
 */
export function getFileTypeTips(
  extensions: string,
  customMaxSize?: number
): string[] {
  if (!extensions) return ["支持所有格式"];

  const extList = extensions.split(",").map(ext => ext.trim().replace(".", ""));
  const tips = [`支持 ${extList.join("、")} 格式`];

  if (customMaxSize !== undefined) {
    tips.unshift(`单个文件最大${customMaxSize}MB`);
  } else {
    // 获取第一个扩展名的默认大小限制
    const firstExt = extensions.split(",")[0]?.trim().toLowerCase();
    const maxSize = DEFAULT_SIZE_LIMITS[firstExt] || 20;
    tips.unshift(`单个文件最大${maxSize}MB`);
  }

  return tips;
}
